/* Copyright Thanh-Trung Pham, JAIST, 2013 */

package jp.ac.jaist.input;

import jp.ac.jaist.ErrorDetectionMatrixType;
import jp.ac.jaist.ErrorDetectionMatrixType.ForFailureType;
import jp.ac.jaist.ErrorDetectionMatrixType.ForFailureType.AsFailureType;
import org.apache.commons.collections.map.MultiKeyMap;

/**
 *
 * @author Thanh-Trung Pham
 */
public class RMPErrorDetectionMatrixWrapper {

    private MultiKeyMap m_oErrorDetectionMatrix;
    private boolean m_bIsCreatedPerfectErrorDetection;
    /**
     * The constructor.
     * @param errorDetectionMatrix an error detection matrix from the reliability modeling schema.
     */
    public RMPErrorDetectionMatrixWrapper(ErrorDetectionMatrixType errorDetectionMatrix) {
        RMPInputModelManager oInputModelManager = RMPInputModelManager.getInstance();

        m_oErrorDetectionMatrix = new MultiKeyMap();

        ForFailureType[] oForFailureTypes = errorDetectionMatrix.getForFailureTypeArray();
        if(oForFailureTypes.length ==0){
            m_bIsCreatedPerfectErrorDetection = true;
            return;
        }

        m_bIsCreatedPerfectErrorDetection = false;

        for (ForFailureType oForFailureType : oForFailureTypes) {
            int r = oInputModelManager.getFailureTypeIndex(oForFailureType.getForFailureType());
            AsFailureType[] oAsFailureTypes = oForFailureType.getAsFailureTypeArray();

            for (AsFailureType oAsFailureType : oAsFailureTypes) {
                int s = oInputModelManager.getFailureTypeIndex(oAsFailureType.getAsFailureType());

                m_oErrorDetectionMatrix.put(r,s, oAsFailureType.getProbability());
            }
        }
    }

    /**
     * Get the detection probability of failure type index r being detected as failure type index s.
     * @param r as described above.
     * @param s as described above.
     * @return the detection probability.
     */
    public double getDp(int r, int s) {
        if(m_bIsCreatedPerfectErrorDetection){
            if(r == s){
                return 1;
            }else{
                return 0;
            }
        }

        if(!m_oErrorDetectionMatrix.containsKey(r, s)){
            return 0;
        }

        return ((Double)m_oErrorDetectionMatrix.get(r, s)).doubleValue();
    }

    /**
     * Get the detection probability of failure type R being detected as failure type S.
     * @param failureTypeR failure type R.
     * @param failureTypeS failure type R.
     * @return the detection probability.
     */
    public double getDp(String failureTypeR, String failureTypeS) {
        RMPInputModelManager oInputModelManager = RMPInputModelManager.getInstance();

        int r = oInputModelManager.getFailureTypeIndex(failureTypeR);
        int s = oInputModelManager.getFailureTypeIndex(failureTypeS);

        return getDp(r,s);
    }
}
